<!-- 岗位管理 -->

<template>
  <div class="client-list">
    <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
      <template #buts>
        <a-button type="primary" @click="handleClick">
          <template #icon>
            <icon-plus />
          </template>
          <template #default>新建岗位</template>
        </a-button>
      </template>
    </pageHeader>

    <tableTurn
      style="margin-top: 10px"
      :tableData="GetPostData"
      :args="args"
      ref="tableTurnRef"
    >
      <a-table-column :width="80" align="center">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column
        v-for="item in selectedHeader"
        :key="item.id"
        :title="item.title"
        :data-index="item.code"
        align="center"
      >
        <template v-if="item.code === 'bu'" #cell="{ record }">
          {{ record.department.name }}
        </template>
        <!-- 状态item -->
        <template v-else-if="item.code === 'state'" #cell="{ record }">
          <div v-if="record.status === 1" class="y_statusBox">
            <span>启用</span>
          </div>
          <div v-else class="n_statusBox">
            <span>停用</span>
          </div>
        </template>

        <template v-else-if="item.code === 'handle'" #cell="{ record }">
          <a-button @click="Modstate(record)" type="text">{{
            record.status === 2 ? '启用' : '停用'
          }}</a-button>
          <a-button @click="compile(record.id)" type="text">编辑</a-button>
          <a-popconfirm
            @ok="deletePosition(record.id)"
            content="确认删除?"
            type="error"
          >
            <a-button type="text" status="danger">删除</a-button>
          </a-popconfirm>
        </template>
      </a-table-column>
    </tableTurn>

    <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
      <template #title> {{ Title }} </template>
      <a-form :model="form" auto-label-width>
        <a-form-item field="name" label="岗位名称">
          <a-input v-model="form.name" />
        </a-form-item>
        <a-form-item field="post" label="岗位编号">
          <a-input v-model="form.code" />
        </a-form-item>
        <a-form-item field="post" label="所属部门">
          <a-cascader
            v-model="form.departmentId"
            :field-names="fieldNames"
            :options="OrganizationData"
            expand-trigger="hover"
          />
        </a-form-item>
        <a-form-item label="启用状态">
          <a-switch
            v-model="form.status"
            :checked-value="1"
            :unchecked-value="2"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { pageData as IpageData } from '@/types/global';
  import { formHeaderSetting } from '@/types/global';
  import {
    GetPositioninformation,
    postPosition,
    modPosition,
    GetsinglePosition,
    DeletePosition,
  } from '@/api/home/System settings/position-management/index';
  import { gainRole } from '@/api/home/System settings/roles-permissions/index';
  import { GetOrganizationchart } from '@/api/home/System settings/organizational-structure/index';

  let Title = ref('');
  const tableTurnRef = ref();
  const router = useRouter();
  const title = '岗位管理';
  const breadCrumb = ['首页', '系统设置', '岗位管理'];
  const args = reactive({
    stripe: true,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    },
    bordered: {
      headerCell: true,
    },
    rowKey: 'name', // 批量选择按钮以客户名称来作为key
  });

  const PostData = ref();
  // 获取岗位信息
  const GetPostData = async () => {
    try {
      const res = await GetPositioninformation({ page: 1, size: -1 });
      return res;
    } catch (err: unknown) {
      console.log(err);
    }
  };

  GetPostData();
  const fieldNames = { value: 'id', label: 'name' };
  const toTree = (list: any) => {
    // 定义最终需要返回的树形结构数据
    let treeData: any = [];
    // 对传入的数组进行遍历
    list.forEach((item: any) => {
      // 如果pid没有值,那就是顶级对象,直接添加进数组
      if (!item.pid) {
        treeData.push(item);
      }
      // 理解为二次遍历 ：每个对象都找一遍自己的孩子添加到children
      let objList = list.filter((data: any) => data.pid === item.id);
      if (objList.length) {
        item.children = objList;
      }
    });
    return treeData;
  };

  const OrganizationData = ref();
  const GetOrganization = async () => {
    const res = await GetOrganizationchart();
    OrganizationData.value = toTree(res.department);
  };
  GetOrganization();

  const visible = ref(false);
  const form = ref<any>({
    id: '',
    name: '',
    post: '',
    status: 1,
    departmentId: undefined,
    code: '',
  });

  const handleClick = () => {
    Title.value = '新建岗位';
    visible.value = true;
    form.value = {
      name: '',
      status: 1,
      departmentId: undefined,
      code: '',
    };
  };

  const handleOk = () => {
    if (Title.value === '新建岗位') {
      postPosition({
        ...form.value,
      }).then((res) => {
        tableTurnRef.value.loadData();
      });
    } else {
      modPosition({
        id: form.value.id,
        number: form.value.number,
        status: form.value.status,
        name: form.value.name,
        roles: [{ userRoleId: Number(form.value.role) }],
      }).then((res) => {
        tableTurnRef.value.loadData();
      });
    }
    visible.value = false;
  };

  const roledata = ref();
  const GainRole = async () => {
    const res = await gainRole();
    roledata.value = res;
  };
  GainRole();

  const compile = (id) => {
    Title.value = '编辑岗位';
    visible.value = true;
    GetsinglePosition({ id }).then((res) => {
      form.value = res;
    });
  };

  const deletePosition = async (id) => {
    const res = await DeletePosition({ id });
    tableTurnRef.value.loadData();
  };

  const handleCancel = () => {};

  const Modstate = (val: any) => {
    modPosition({
      id: val.id,
      name: val.fname,
      roles: [{ userRoleId: 134 }],
      status: val.status === 1 ? 2 : 1,
    }).then((res) => {
      tableTurnRef.value.loadData();
    });
  };

  const columns = [
    {
      id: 1,
      title: '岗位名称',
      visible: true,
      type: 'string',
      code: 'name',
    },
    {
      id: 2,
      title: '岗位编号',
      visible: true,
      type: 'string',
      code: 'code',
    },
    {
      id: 3,
      title: '归属部门',
      visible: true,
      type: 'string',
      code: 'bu',
    },
    {
      id: 4,
      title: '状态',
      visible: true,
      type: 'string',
      code: 'state',
    },
    {
      id: 5,
      title: '操作',
      visible: true,
      type: 'string',
      code: 'handle',
    },
  ];

  const selectedHeader = computed(() => {
    const arr: any = [];
    columns.forEach((item) => {
      if (item.visible) {
        arr.push(item);
      }
    });
    return arr;
  });

  const headerSetting = reactive<formHeaderSetting>({
    list: [],
  });

  // 储存岗位信息
  const clientList = reactive([]);

  // 点击新建岗位
  // const add = (): void => {
  // };

  let formHeaderSettingVisible = ref<boolean>(false); // 是否显示表头设置组件
</script>

<style scoped lang="less">
  .client-list {
    :deep(.arco-space) {
      justify-content: space-between;
    }
    :deep(.arco-space-horizontal .arco-space-item) {
      margin-left: 50px;
    }

    .y_statusBox {
      width: 60px;
      height: 30px;
      background-color: rgba(49, 194, 124, 1);
      border-radius: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
    }

    .n_statusBox {
      width: 60px;
      height: 30px;
      background-color: rgba(204, 204, 204, 1);
      border-radius: 100px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
    }
  }
</style>
